<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    * {
        padding: 0;
        margin: 0;
    }

    canvas {
        display: block;
        background: black;
    }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var data = []; //雨滴数组
    var w, h;

    init();

    function init() {
        w = window.innerWidth;
        h = window.innerHeight;
        canvas.width = w;
        canvas.height = h;
    }
    window.onresize = init;



    /*声明一个雨滴类*/
    function Rain() {}
    Rain.prototype = {
        /*初始化雨滴的属性*/
        init: function() {
            this.x = random(0, w);
            this.y = 0;
            this.w = 2;
            this.h = 10;
            this.speedY = random(8, 10);
            this.r = 1;
            this.vr = 1;
            this.a = 1;
            this.va = 0.96;
            this.color = 'rgb(0,255,255)';
            this.destination = random(0.8 * h, 0.9 * h); /*雨滴下落的终点*/

        },
        /*画雨滴的方法*/
        draw: function() {
            if (this.y < this.destination) {
                ctx.beginPath();
                ctx.fillStyle = this.color;
                ctx.fillRect(this.x, this.y, this.w, this.h);
            } else {
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
                ctx.strokeStyle = this.color;
                ctx.stroke();
            }

        },
        /*雨滴下落运动*/
        move: function() {
            if (this.y < this.destination) {
                this.y += this.speedY;
            } else {
                if (this.r > 120) {
                    this.init();
                }
                this.r += this.vr;

            }
            this.draw();
        }
    };
    createRain(66);
    /*创建雨滴*/
    function createRain(num) {
        for (var i = 0; i < num; i++) {
            /*定时器是一个异步,for循环结束,定时器还没有开始,因此产生了66个间隔600ms的定时,最后还是一起出来,所以我们要通过循环 改变他的间隔时间*/
            setTimeout(function() {
                var rain = new Rain();
                rain.init();
                data.push(rain);
            }, i * 600)
        }
    }

    moveRain();
    /*雨滴运动*/
    function moveRain() {
        requestAnimationFrame(moveRain);
        /*画之前先在上面盖上一个透明层,这样形成视觉差雨滴有一个后缀*/
        ctx.fillStyle = 'rgba(0,0,0,0.1)';
        ctx.fillRect(0, 0, w, h);

        for (var item of data) {
            item.move();
        }
    }

    function random(min, max) {
        return Math.random() * (max - min) + min;
    }
    </script>
</body>

</html>